﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace RFW.Weather
{
	public abstract class Communication
	{
		public string LocationCode { get; set; }
		internal string URI { get; set; }
        public bool AreResultsXML { get; set; }

		public event System.EventHandler DownloadComplete;
		public event System.EventHandler DownloadFailed;

		public Communication(string locationCode, string URI, bool areResultsXML)
		{
			this.LocationCode = locationCode;
			this.URI = URI;
            this.AreResultsXML = areResultsXML;
		}

        public Communication(string URI, bool areResultsXML)
        {
            this.LocationCode = string.Empty;
            this.URI = URI;
            this.AreResultsXML = areResultsXML;
        }

		public abstract void Process(XDocument results);
        public abstract void Process(string results);
		internal abstract void Failed();

		public virtual void Get()
		{
			try
			{
				System.Net.WebClient wc = new WebClient();
				wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);

                Uri uri = new Uri(this.URI);
                if (this.LocationCode.Trim().Length > 0)
                    uri = new Uri(string.Format(this.URI, this.LocationCode));

				wc.DownloadStringAsync(uri);
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				if (DownloadFailed != null)
					DownloadFailed(this, EventArgs.Empty);
			}
		}

		private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
            bool failed = false;

			try
			{
                if (e.Error == null)
                {
                    if (this.AreResultsXML)
                    {
                        XDocument doc = XDocument.Parse(e.Result);

                        Process(doc);
                        if (DownloadComplete != null)
                            DownloadComplete(this, EventArgs.Empty);
                    }
                    else
                    {
                        Process(e.Result);
                        if (DownloadComplete != null)
                            DownloadComplete(this, EventArgs.Empty);
                    }
                }
			}
			catch (Exception ex)
			{
                failed = true;
				System.Diagnostics.Debug.WriteLine(ex.Message);
			}

            if (failed)
            {
                Failed();

                if (DownloadFailed != null)
                    DownloadFailed(this, EventArgs.Empty);
            }
		}
	}
}
